package com.bestcem.xm.common.core.uitls;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.msgpack.jackson.dataformat.MessagePackFactory;

import java.io.IOException;
import java.util.Map;

/**
 * msgPack格式化工具类
 *
 * @author sh.pei <sh.pei@idiaoyan.com>
 * @version v1.0
 * @date 2021/8/1 15:22
 */
public class MsgPackFormatUtil {
    /**
     * 类型转换工具类 map到实体类
     */
    public static <T> T mapToObj(Map<String, Object> map, Class<T> clazz) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper(new MessagePackFactory());
        byte[] bytes = objectMapper.writeValueAsBytes(map);
        return objectMapper.readValue(bytes, clazz);
    }

    /**
     * mq加密
     **/
    public static byte[] encode(Object obj) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper(new MessagePackFactory());
        return objectMapper.writeValueAsBytes(obj);
    }

    /**
     * mq解密
     **/
    public static <T> T decode(byte[] bytes, Class<T> clazz) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper(new MessagePackFactory());
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return objectMapper.readValue(bytes, clazz);
    }

}
